package com.videoweb.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.videoweb.mapper.CommentMapper;
import com.videoweb.model.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.videoweb.model.User;

@Service
public class CommentService extends ServiceImpl<CommentMapper, Comment> {
    
    @Autowired
    private CommentMapper commentMapper;
    
    @Autowired
    private UserService userService;
    
    public Comment createComment(Long videoId, String content, String commenter) {
        Comment comment = new Comment();
        comment.setVideoId(videoId);
        comment.setContent(content);
        comment.setCommenter(commenter);
        comment.setCreatedAt(LocalDateTime.now());

        // 获取当前登录用户
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getPrincipal())) {
            User user = userService.getCurrentUser(auth.getName()).orElse(null);
            if (user != null) {
                comment.setUserId(user.getId());
            }
        }

        commentMapper.insert(comment);
        return comment;
    }
    
    public List<Comment> getCommentsByVideoId(Long videoId) {
        return commentMapper.findByVideoIdOrderByCreatedAtDesc(videoId);
    }
}